//
//  GroupListVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/24.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "GroupListVC.h"
#import "SearchFriendResultVC.h"
#import "GroupListCell.h"
#import "GroupDetailVC.h"
#import "FriendInfoListVC.h"
#import "ChatContentVC.h"
#import <LKDBHelper/LKDBHelper.h>

@interface GroupListVC ()

@property (nonatomic, strong) UISearchController *searchVC;
@property (nonatomic, weak) SearchFriendResultVC *resultVC;
@end

@implementation GroupListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"群聊";
    [self setupUI];
    
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_GroupChatList_updated object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self.tableView reloadData];
    }];
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_GroupChatInfo_updated object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        GroupItem *group = x.object;
        for (GroupItem *obj in kUsermanager.groupChatArray) {
            if ([obj isEqual:group] == YES) {
                [obj mj_setKeyValues:group];
                [self.tableView reloadData];
                break;
            }
        }
    }];
}
- (void)setupUI {
    self.pContentView.type = 666;
    [self.tableView customRegisterClassWithName:@"GroupListCell"];
}
- (void)setupSearchVc {
    self.extendedLayoutIncludesOpaqueBars = !self.navigationController.navigationBar.translucent;
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTintColor:UIColor.k_t2Color];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTitle:@"取消"];
    
    SearchFriendResultVC *resultVC = [SearchFriendResultVC new];
    @weakify(self);
    [resultVC setDidSelectFriendItemBlock:^(FriendItem * _Nonnull item) {
        @strongify(self);
        [self showFriendInfoVCWithType:2 friendItem:item from:@"0"];
    }];
    self.resultVC = resultVC;
    self.searchVC = [[UISearchController alloc] initWithSearchResultsController:resultVC];
    
    self.searchVC.searchResultsUpdater = resultVC;
    self.searchVC.searchBar.delegate = resultVC;
    self.searchVC.delegate = resultVC;
    
    // 1.设置placeholder
    self.searchVC.searchBar.placeholder = @"搜索好友";
    
    // 2.设置searchBar的背景透明
    [self.searchVC.searchBar setBackgroundImage:[UIImage new]];
    self.searchVC.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
    // 3.设置搜索框文字的偏移
    self.searchVC.searchBar.searchTextPositionAdjustment = UIOffsetMake(3, 0);
    
    // 4.设置搜索框图标的偏移
    //    CGFloat offsetX = (self.view.bounds.size.width - 200 - 32) / 2;
    //    [self.searchVC.searchBar setPositionAdjustment:UIOffsetMake(offsetX, 0) forSearchBarIcon:UISearchBarIconSearch];
    
    // 5.取消按钮和文本框光标颜色
    //    self.searchVC.searchBar.tintColor = UIColor.k_t1Color;
    //    self.searchVC.searchBar.barTintColor = UIColor.k_t1Color;
    
    // 6.设置搜索文本框背景图片 [圆形的文本框只需要设置一张圆角图片就可以了]
    
    [self.searchVC.searchBar setSearchFieldBackgroundImage:[UIImage.k_imgFillColor(UIColor.k_hexColor(0xf0f0f0), CGSizeMake(ScreenWidth - 100, 36)) imageWithCornerRadius:36/2] forState:UIControlStateNormal];
    // 7.设置搜索按钮
    UIImage *searchImg = [[UIImage imageNamed:@"new_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.searchVC.searchBar setImage:searchImg forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    
    [self.searchVC.searchBar sizeToFit];
    
    
    // 2.Install the search bar
    if ([self.navigationItem respondsToSelector:@selector(setSearchController:)]) {
        // 2.1 For iOS 11 and later, wo place the search bar in the navigation bar
        if (@available(iOS 11.0, *)) {
            self.navigationItem.searchController = self.searchVC;
            // 2.2 Set the search bar visible all the time
            self.navigationItem.hidesSearchBarWhenScrolling = NO;
        }
        
    } else {
        UIView *v = [[UIView alloc] initWithFrame:self.searchVC.searchBar.bounds];
        v.frame = CGRectMake(v.frame.origin.x, 64, v.frame.size.width, v.frame.size.height);
        v.backgroundColor = UIColor.whiteColor;
        [v addSubview:self.searchVC.searchBar];
        
        //    self.tableView.tableHeaderView = v;
        [self.view addSubview:v];
    }
    
    // 3.It is usually good to set the presentation context
    self.definesPresentationContext = YES;
    
    // 8.拿到搜索文本框
    UITextField *searchField = [self.searchVC.searchBar valueForKey:@"_searchField"];
    //    // 9.设置取消按钮文字
    //    [self.searchVC.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
    //
    searchField.font = [UIFont systemFontOfSize:14];
}

#pragma mark - tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return kUsermanager.groupChatArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GroupListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupListCell" forIndexPath:indexPath];
    GroupItem *group = kUsermanager.groupChatArray[indexPath.row];
    cell.group = group;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GroupItem *group = kUsermanager.groupChatArray[indexPath.row];
//    GroupDetailVC * detailVC = GroupDetailVC.new;
//    detailVC.group = group;
//    [self.navigationController pushViewController:detailVC animated:YES];
    
    SessionItem *session = [SessionItem searchSingleWithWhere:@{@"group_id": group.group_id} orderBy:nil];
    if (session == nil) {
        session = [SessionItem new];
        session.group_id = group.group_id;
        session.groupIcon = group.avatar;
        session.groupName = group.name;
        session.isGroupChat = YES;
        [SessionItem insertToDB:session];
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_NewSession_created object:session];
    }
    ChatContentVC *chatVc = [ChatContentVC new];
    chatVc.session = session;
    [self.navigationController pushViewController:chatVc animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)showFriendInfoVCWithType:(NSInteger)type friendItem:(FriendItem *)item from:(NSString *)from {
    FriendInfoListVC *VC = [FriendInfoListVC new];
    VC.user = item;
    VC.from = from;
    VC.listType = type;
    
    [self.navigationController pushViewController:VC animated:YES];
}

@end
